package com.walixiwa.m3udownloader.adapter;

import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.walixiwa.m3udownloader.R;
import com.walixiwa.m3udownloader.model.DownloadTaskModel;

import java.util.List;


public class DownloadAdapter extends RecyclerView.Adapter<DownloadAdapter.MyViewHolder> {
    private List<DownloadTaskModel> tasks;

    public DownloadAdapter(List<DownloadTaskModel> tasks) {
        this.tasks = tasks;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = View.inflate(parent.getContext(), R.layout.item_download, null);
        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull final MyViewHolder holder, int position) {
        final DownloadTaskModel model = tasks.get(position);
        holder.mTvTitle.setText(model.getName());
        holder.mProgressBar.setProgress(model.getProgress());
        holder.mTvInfo.setText(model.getInfo());
        holder.mTvSpeed.setText(model.getSpeed());
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onItemClickListener != null) {
                    onItemClickListener.onItemClick(holder.getAdapterPosition(), model);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return tasks.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView mTvTitle;
        public TextView mTvInfo;
        public TextView mTvSpeed;
        public ProgressBar mProgressBar;

        private MyViewHolder(View viewRoot) {
            super(viewRoot);
            mTvTitle = viewRoot.findViewById(R.id.tv_title);
            mTvInfo = viewRoot.findViewById(R.id.tv_info);
            mTvSpeed = viewRoot.findViewById(R.id.tv_speed);
            mProgressBar = viewRoot.findViewById(R.id.pb_progress);
        }
    }


    private OnItemClickListener onItemClickListener;

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public interface OnItemClickListener {
        void onItemClick(int position, DownloadTaskModel model);
    }
}
